package com.tuanzhang.zhw.rpc.spring;

import com.tuanzhang.zhw.rpc.config.consumer.RpcClientConfig;
import com.tuanzhang.zhw.rpc.config.provider.RpcServerConfig;
import com.tuanzhang.zhw.rpc.register.RpcRegistryConsumerService;
import com.tuanzhang.zhw.rpc.register.zookeeper.CuratorImpl;
import com.tuanzhang.zhw.rpc.register.zookeeper.RpcRegistryProviderService;
import com.tuanzhang.zhw.rpc.register.zookeeper.ZookeeperClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;

/**
 * rpc 配置
 */
@Slf4j
@Configuration
public class RpcConfig {

    @Autowired
    private Environment environment;

    @Bean
    public ZookeeperClient zookeeperClient(){
        String zkAddress = environment.getProperty("zk.zookeeper.address");
        ZookeeperClient curator = new CuratorImpl(zkAddress, 1000);
        return curator;
    }

    @Bean
    public RpcRegistryConsumerService rpcRegistryConsumerService() throws Exception {
       return new RpcRegistryConsumerService(zookeeperClient());
    }

    @Bean
    public RpcRegistryProviderService rpcRegistryProviderService() throws Exception {
        return  new RpcRegistryProviderService(zookeeperClient());
    }

    @Bean
    public RpcClientConfig rpcClientConfig() throws Exception {
        return  new RpcClientConfig(rpcRegistryConsumerService());
    }

    @EventListener
    public void handler(ApplicationReadyEvent applicationReadyEvent) throws Exception {
        String consumer = environment.getProperty("zhw-rpc", "consumer");
        if(!consumer.equals("consumer")) {
            log.info("applicationReadyEvent 启动【zhw-rpc】 server...");
            // 服务端配置
            RpcServerConfig rpcServerConfig = new RpcServerConfig(rpcRegistryProviderService());
            rpcServerConfig.setPort(8765);
            rpcServerConfig.exporter();
        }
    }

}
